#!/bin/bash

echo "启动产业链可视化系统..."
echo

# 检查Python环境
if ! command -v python3 &> /dev/null; then
    echo "错误: 未找到Python3，请先安装Python3"
    exit 1
fi

# 检查Node.js环境
if ! command -v node &> /dev/null; then
    echo "错误: 未找到Node.js，请先安装Node.js"
    exit 1
fi

# 检查MySQL服务
if ! command -v mysql &> /dev/null; then
    echo "警告: 未找到MySQL，请确保MySQL服务已启动"
fi

echo "1. 启动后端服务..."
cd backend

# 检查虚拟环境
if [ ! -d "venv" ]; then
    echo "创建Python虚拟环境..."
    python3 -m venv venv
fi

# 激活虚拟环境
source venv/bin/activate

# 安装依赖
if [ ! -f ".installed" ]; then
    echo "安装Python依赖..."
    pip install -r requirements.txt
    touch .installed
fi

# 启动Flask应用
echo "启动Flask应用..."
python app.py &
BACKEND_PID=$!

echo "2. 等待后端启动..."
sleep 3

echo "3. 启动前端服务..."
cd ../frontend

# 安装前端依赖
if [ ! -d "node_modules" ]; then
    echo "安装前端依赖..."
    npm install
fi

# 启动前端开发服务器
echo "启动前端开发服务器..."
npm run serve &
FRONTEND_PID=$!

echo
echo "系统启动完成！"
echo "后端地址: http://localhost:5000"
echo "前端地址: http://localhost:8080"
echo
echo "按Ctrl+C停止所有服务"

# 等待用户中断
trap "echo '正在停止服务...'; kill $BACKEND_PID $FRONTEND_PID; exit" INT
wait